package cn.edu.xaut.Dao;

import cn.edu.xaut.bean.User;
import cn.edu.xaut.util.JDBCUtils;

import java.sql.*;

public class UsersDao {
    public boolean insert(User user)throws SQLException,ClassNotFoundException{
        //使用Dao来插入数据
        Connection conn= JDBCUtils.getConnection();

        String sql="insert into user(username,password,email,registerdate) values(?,?,?,?)";
        PreparedStatement ps=conn.prepareStatement(sql);

        //设置参数,占位符
        ps.setString(1,user.getUsername());
        ps.setString(2,user.getPassword());
        ps.setString(3,user.getEmail());
        ps.setDate(4,user.getRegisterdate());

        //执行SQL语句
        int update=ps.executeUpdate();

        //关闭数据库连接
        JDBCUtils.release(ps,conn);

        if (update>0)
            return true;
        else
            return false;

    }

    public User findOne(String username,String password)throws SQLException,ClassNotFoundException{
        User user=null;

        //使用Dao来查询数据
        Connection conn=JDBCUtils.getConnection();
        Statement stmt=conn.createStatement();
        String sql="select * from user where username='"+username+"' and password='"+password+"'";
        ResultSet rs=stmt.executeQuery(sql);

        if(rs.next()){
            user=new User();
            user.setId(rs.getInt("id"));
            user.setUsername(rs.getString("username"));
            user.setPassword(rs.getString("password"));
            user.setEmail(rs.getString("email"));
            user.setRegisterdate(rs.getDate("registerdate"));
        }
        JDBCUtils.release(rs,stmt,conn);
        return user;
    }

    public User findbyname(String username)throws SQLException,ClassNotFoundException{
        User user=null;

        //使用Dao来查询数据
        Connection conn=JDBCUtils.getConnection();
        Statement stmt=conn.createStatement();
        String sql="select * from user where username='"+username+"'";
        ResultSet rs=stmt.executeQuery(sql);

        if(rs.next()){
            user=new User();
            user.setId(rs.getInt("id"));
            user.setUsername(rs.getString("username"));
            user.setPassword(rs.getString("password"));
            user.setEmail(rs.getString("email"));
            user.setRegisterdate(rs.getDate("registerdate"));
        }
        JDBCUtils.release(rs,stmt,conn);
        return user;
    }
}

